package com.zb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.constant.NetworkConstant;
import com.zb.entity.*;
import com.zb.extend.NetworkEmpLevelRelationExtend;
import com.zb.extend.NetworkEmpRelationExtend;
import com.zb.extend.NetworkEmpSkillRelationExtend;
import com.zb.mapper.ZjNetworkEmpMapper;
import com.zb.result.PageUtil;
import com.zb.service.*;
import com.zb.view.ViewNetworkEmpDetail;
import com.zb.vo.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 网点人员表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-10-18
 */
@Service
public class ZjNetworkEmpServiceImpl extends ServiceImpl<ZjNetworkEmpMapper, ZjNetworkEmp> implements ZjNetworkEmpService {
    @Resource
    private ZjNetworkEmpMapper networkEmpMapper;
    @Resource
    private ZjNetworkEmpRelationService networkEmpRelationService;
    @Resource
    private ZjNetworkService networkService;
    @Resource
    private ZjAccountService accountService;
    @Resource
    private ViewNetworkEmpDetailService viewNetworkEmpDetailService;
    @Resource
    private ZjNetworkEmpFieldValService networkEmpFieldValService;
    @Resource
    private ZjNetworkEmpFieldValOptionService networkEmpFieldValOptionService;
    @Resource
    private ZjNetworkEmpAddressService networkEmpAddressService;
    @Resource
    private ZjNetworkEmpLevelRelationService networkEmpLevelRelationService;
    @Resource
    private ZjNetworkEmpSkillRelationService networkEmpSkillRelationService;


    @Override
    public Long saveNetworkManager(Long accountId) {
        ZjNetworkEmp networkEmp = networkEmpMapper.getByAccountId(accountId);
        if (null == networkEmp) {
            networkEmp = new ZjNetworkEmp();
            networkEmp.setId(IdWorker.getId());
            networkEmp.setAccountId(accountId);
            networkEmp.setAutoSureReceiveOrder(true);
            this.save(networkEmp);
        }
        return networkEmp.getId();
    }

    // 新增或修改服务商人员
    @Override
    @Transactional
    public void save(Long custAccId, NetworkEmpVo networkEmpVo) {
        if (null != networkEmpVo.getNetworkId() && (null == networkEmpVo.getId() || networkEmpVo.getId() == 0)) {
            ZjNetwork network = networkService.getById(networkEmpVo.getNetworkId());
            Assert.notNull(network, "服务商ID参数的数据不存在：" + networkEmpVo.getNetworkId());
            Assert.isTrue(network.getTeamType() == NetworkConstant.NETWORK_TEAM_TYPE_1, "当前服务商团队模式为个人，不允许添加人员");
        }
        if (null != networkEmpVo.getId() && CollectionUtils.isNotEmpty(networkEmpVo.getDelNetworkIds())) {
            List<ZjNetworkEmpRelation> empRelations = networkEmpRelationService.getManagerByNetworkEmpIdAndNetworkIds(networkEmpVo.getId(), networkEmpVo.getDelNetworkIds());
            if (CollectionUtils.isNotEmpty(empRelations)) {
                QueryWrapper<ZjNetwork> networkQueryWrapper = new QueryWrapper<>();
                networkQueryWrapper.select("name");
                networkQueryWrapper.in("id", empRelations.stream().map(ZjNetworkEmpRelation::getNetworkId).distinct().toList());
                String networkNames = networkService.list(networkQueryWrapper).stream().map(ZjNetwork::getName).collect(Collectors.joining("、"));
                Assert.isTrue(false, "服务人员["+ networkEmpVo.getAccountUserName() +"]是服务区域["+ networkNames +"]的负责人，不可删除");
            }
            networkEmpRelationService.deleteByNetworkEmpAndNetworkIds(networkEmpVo.getId(), networkEmpVo.getDelNetworkIds());
        }
        // 修改人员时，判断修改的人员状态为离职时，人员是否为服务商负责人
        if (null != networkEmpVo.getId() && 0 != networkEmpVo.getId() && networkEmpVo.getQuit()) {
            if (null != networkEmpVo.getNetworkId() && networkEmpVo.getNetworkId() != 0) {
                // 根据人员ID获取是否为服务商的负责人
                ZjNetworkEmpRelation empRelation = networkEmpRelationService.getNetworkEmpIdAndNetworkId(networkEmpVo.getId(), networkEmpVo.getNetworkId());
                Assert.isFalse(null != empRelation && empRelation.getManager(), "当前人员为服务商负责人，禁止更改状态为离职！如需更改，请更换负责人后重试");
            } else {
                List<ZjNetworkEmpRelation> empRelationList = networkEmpRelationService.getManagerByCustAccIdAndNetworkEmpId(custAccId, networkEmpVo.getId());
                if (CollectionUtil.isNotEmpty(empRelationList)) {
                    List<Long> networkIds = empRelationList.stream().map(ZjNetworkEmpRelation::getNetworkId).distinct().toList();
                    if (CollectionUtil.isNotEmpty(networkIds)) {
                        List<String> networks = networkService.getNameByIds(networkIds).stream().map(ZjNetwork::getName).toList();
                        Assert.isTrue(false, "当前人员为服务商负责人，禁止更改状态为离职！如需更改，请更换负责人后重试！负责的服务商：" + String.join("、", networks));
                    }
                }
            }
        }
        Long accountId = accountService.getOrSave(networkEmpVo.getAccountId(), networkEmpVo.getAccountUserPhone(), null, networkEmpVo.getAccountUserName(), null);
        ZjNetworkEmp networkEmp = networkEmpMapper.getByAccountId(accountId);
        networkEmpVo.setAccountId(accountId);
        if (null != networkEmp) {
            networkEmp.setAutoSureReceiveOrder(networkEmpVo.getAutoSureReceiveOrder());
            this.updateById(networkEmp);
        } else {
            networkEmp = new ZjNetworkEmp();
            networkEmp.setId(IdWorker.getId());
            networkEmp.setAccountId(networkEmpVo.getAccountId());
            networkEmp.setAutoSureReceiveOrder(networkEmpVo.getAutoSureReceiveOrder());
            this.save(networkEmp);
        }
//        if (null != networkEmpVo.getId() && 0 != networkEmpVo.getId()) {
//            networkEmp = new ZjNetworkEmp();
//            networkEmp.setId(networkEmpVo.getId());
//            networkEmp.setAutoSureReceiveOrder(networkEmpVo.getAutoSureReceiveOrder());
//            this.updateById(networkEmp);
//        } else {
//            networkEmpVo.setAccountId(accountId);
//            networkEmp = networkEmpMapper.getByAccountId(networkEmpVo.getAccountId());
//            if (null == networkEmp) {
//                networkEmp = new ZjNetworkEmp();
//                networkEmp.setId(IdWorker.getId());
//                networkEmp.setAccountId(networkEmpVo.getAccountId());
//                networkEmp.setAutoSureReceiveOrder(networkEmpVo.getAutoSureReceiveOrder());
//                this.save(networkEmp);
//            } else {
//                this.updateById(networkEmp);
//            }
//        }
        // 1. 使用UpdateWrapper构建更新条件
        UpdateWrapper<ZjNetworkEmpLevelRelation> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("cust_acc_id", custAccId)
                .eq("network_emp_id", networkEmp.getId());
        // 2. 创建要更新的实体对象
        ZjNetworkEmpLevelRelation updateEntity = new ZjNetworkEmpLevelRelation();
        updateEntity.setNetworkEmpLevelId(networkEmpVo.getNetworkEmpLevelId());  // 设置新的等级
        updateEntity.setManualLevel(networkEmpVo.getManualLevel());         // 是否设置手动调整
        // 3. 执行更新
        networkEmpLevelRelationService.save(custAccId, networkEmp.getId(), networkEmpVo.getNetworkEmpLevelId());
        networkEmpRelationService.save(custAccId, networkEmp.getId(), networkEmpVo);
        networkEmpSkillRelationService.save(custAccId, networkEmp.getId(), networkEmpVo.getNetworkEmpSkillIds());
        networkEmpFieldValService.save(custAccId, networkEmp.getId(), networkEmpVo.getFieldVals());
        boolean success = networkEmpLevelRelationService.update(updateEntity, updateWrapper);
    }

    // 获取服务人员列表
    @Override
    public Map<String, Object> getList(Long custAccId, NetworkEmpSelectVo selectVo) {
        PageUtil.setPageLimit(selectVo);
        long count = viewNetworkEmpDetailService.getNetworkEmpListCount(custAccId, selectVo);
        if (count <= 0) {
            return PageUtil.pageList(selectVo.getPage(), selectVo.getLimit(), count, new ArrayList<>());
        }
        List<NetworkEmpListVo> voList = viewNetworkEmpDetailService.getNetworkEmpList(custAccId, selectVo);
        List<Long> networkEmpIds = voList.stream().map(NetworkEmpListVo::getId).toList();
        List<NetworkEmpLevelRelationExtend> empLevelRelationExtends = networkEmpLevelRelationService.getByNetworkEmpIds(custAccId, networkEmpIds);
        List<NetworkEmpSkillRelationExtend> empSkillRelationExtends = networkEmpSkillRelationService.getByNetworkIds(custAccId, networkEmpIds);
        voList.forEach(t -> {
            empLevelRelationExtends.stream().filter(f -> Objects.equals(f.getNetworkEmpId(), t.getId()))
                    .findFirst().map(NetworkEmpLevelRelationExtend::getNetworkLevel)
                    .ifPresent(t::setNetworkEmpLevel);
            t.setNetworkEmpSkill(empSkillRelationExtends.stream().filter(f -> Objects.equals(f.getNetworkEmpId(), t.getId()))
                    .map(NetworkEmpSkillRelationExtend::getNetworkEmpSkill).collect(Collectors.joining("、")));
        });
        return PageUtil.pageList(selectVo.getPage(), selectVo.getLimit(), count, voList);
    }

    // 获取服务商详情之服务商人员列表
    @Override
    public Map<String, Object> getNetworkDetailEmpList(Long custAccId, Long networkId, PageUtil pageUtil) {
        PageUtil.setPageLimit(pageUtil);
        long count = viewNetworkEmpDetailService.getNetworkDetailEmpListCount(networkId);
        if (count <= 0) {
            return PageUtil.pageList(pageUtil.getPage(), pageUtil.getLimit(), count, new ArrayList<>());
        }
        List<ViewNetworkEmpDetail> empDetailViews = viewNetworkEmpDetailService.getNetworkDetailEmpList(networkId, pageUtil);
        List<Long> networkEmpIds = empDetailViews.stream().map(ViewNetworkEmpDetail::getId).toList();
        List<NetworkEmpLevelRelationExtend> empLevelRelationExtends = networkEmpLevelRelationService.getByNetworkEmpIds(custAccId, networkEmpIds);
        List<NetworkEmpSkillRelationExtend> empSkillRelationExtends = networkEmpSkillRelationService.getByNetworkIds(custAccId, networkEmpIds);
        List<NetworkDetailEmpListVo> voList = empDetailViews.stream().map(emp -> {
            NetworkDetailEmpListVo vo = new NetworkDetailEmpListVo();
            BeanUtil.copyProperties(emp, vo);
            vo.setEmpRealtionId(emp.getNetworkEmpRelationId());
            vo.setUserName(emp.getAccountName());
            vo.setUserPhone(emp.getAccountPhone());
            empLevelRelationExtends.stream().filter(f -> Objects.equals(f.getNetworkEmpId(), emp.getId()))
                    .findFirst().map(NetworkEmpLevelRelationExtend::getNetworkLevel)
                    .ifPresent(vo::setNetworkEmpLevel);
            vo.setNetworkEmpSkill(empSkillRelationExtends.stream().filter(f -> Objects.equals(f.getNetworkEmpId(), emp.getId()))
                    .map(NetworkEmpSkillRelationExtend::getNetworkEmpSkill).collect(Collectors.joining("、")));
            return vo;
        }).toList();
        return PageUtil.pageList(pageUtil.getPage(), pageUtil.getLimit(), count, voList);
    }

    // 根据服务人员ID获取服务人员详情
    @Override
    public NetworkEmpVo getDetail(Long custAccId, Long id, Long empRelationId) {
       // ZjNetworkEmp networkEmp = this.getById(id);
        QueryWrapper<ZjNetworkEmp> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        ZjNetworkEmp networkEmp = networkEmpMapper.selectOne(queryWrapper);
    //   ZjNetworkEmp networkEmp = this.getByAccountId(id);
        Assert.isTrue(null != networkEmp, "服务人员ID参数["+ id +"]的数据不存在");
        ZjAccount account = accountService.getById(networkEmp.getAccountId());
        ZjNetworkEmpRelation empRelation = networkEmpRelationService.getById(empRelationId);
        List<ZjNetworkEmpFieldVal> fieldVals = networkEmpFieldValService.getByNetworkEmpId(custAccId, id);
        List<ZjNetworkEmpFieldValOption> optionList = networkEmpFieldValOptionService.getByNetworkEmpId(custAccId, id);

        NetworkEmpVo vo = new NetworkEmpVo();
        vo.setId(networkEmp.getId());
        vo.setAccountId(account.getId());
        vo.setAutoSureReceiveOrder(networkEmp.getAutoSureReceiveOrder());
        vo.setAccountUserName(account.getName());
        vo.setAccountUserPhone(account.getPhone());
        if (null != empRelation) {
            vo.setSuperManager(empRelation.getSuperManager());
            vo.setQuit(empRelation.getQuit());
        }
        vo.setFieldVals(fieldVals.stream().map(val -> {
            NetworkFieldValVo fieldValVo = new NetworkFieldValVo();
            BeanUtil.copyProperties(val, fieldValVo);
            fieldValVo.setFieldId(val.getNetworkEmpFieldId());
            fieldValVo.setOptVos(optionList.stream().filter(f -> Objects.equals(f.getNetworkEmpFieldValId(), val.getId())).map(opt -> {
                return new FieldValOptionVo(opt.getId(), opt.getOptValue());
            }).toList());
            return fieldValVo;
        }).toList());
        vo.setNetworkEmpLevelId(networkEmpLevelRelationService.getNetworkEmpLevelIdByNetworkEmpId(custAccId, id));
        vo.setManualLevel(networkEmpLevelRelationService.getNetworkEmpLevellevelStausByNetworkEmpId(custAccId, id));
        vo.setNetworkEmpSkillIds(networkEmpSkillRelationService.getNetworkEmpSkillIdsByNetworkEmpId(custAccId, id));
        return vo;
    }

    // 根据服务人员关联ID删除服务商人员
    @Override
    public void deleteNetworkEmp(Long empRelationId) {
        ZjNetworkEmpRelation empRelation = networkEmpRelationService.getById(empRelationId);
        Assert.isTrue(!empRelation.getManager(), "该人员为服务商负责人，不可删除");
        networkEmpRelationService.removeById(empRelationId);
    }

    // 根据服务人员ID获取人员信息
    @Override
    public ViewNetworkEmpDetail getInfoById(Long id) {
        ZjNetworkEmp networkEmp = this.getById(id);
        if (null == networkEmp) {
            return null;
        }
        ZjAccount account = accountService.getById(networkEmp.getAccountId());

        ViewNetworkEmpDetail detailView = new ViewNetworkEmpDetail();
        detailView.setAccountId(account.getId());
        detailView.setAccountName(account.getName());
        detailView.setAccountPhone(account.getPhone());
        return detailView;
    }

    // 根据服务人员ID获取人员信息
    @Override
    public List<ViewNetworkEmpDetail> getInfoByIds(List<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjNetworkEmp> wrapper = new QueryWrapper<>();
        wrapper.select("id", "accountId");
        wrapper.in("id", ids);
        List<ZjNetworkEmp> networkEmpList = this.list(wrapper);
        List<Long> accountIds = networkEmpList.stream().map(ZjNetworkEmp::getAccountId).toList();
        List<ZjAccount> accountList = accountService.getByIds(accountIds);
        return networkEmpList.stream().map(emp -> {
            ViewNetworkEmpDetail empVo = new ViewNetworkEmpDetail();
            empVo.setId(emp.getId());
            empVo.setAccountId(emp.getAccountId());
            ZjAccount account = accountList.stream().filter(f -> Objects.equals(f.getId(), emp.getAccountId())).findFirst().orElse(null);
            if (null != account) {
                empVo.setAccountName(account.getName());
                empVo.setAccountPhone(account.getPhone());
            }
            return empVo;
        }).toList();
    }

    // 获取服务商人员下拉数据
    @Override
    public Map<String, Object> getNetworkEmpPageSelect(Long networkId, SelectVo selectVo) {
        PageUtil.setPageLimit(selectVo);
        List<ViewNetworkEmpDetail> empDetailViews = viewNetworkEmpDetailService.getNetworkEmpPageSelect(networkId, selectVo);
        List<SelectEmpVo> voList = empDetailViews.stream().map(emp -> {
            return new SelectEmpVo(emp.getId(), emp.getAccountName(), emp.getAccountPhone());
        }).toList();
        return PageUtil.pageList(selectVo.getPage(), selectVo.getLimit(), viewNetworkEmpDetailService.getNetworkEmpPageSelectCount(networkId, selectVo), voList);
    }

    // 根据账号ID获取服务商人员信息
    @Override
    public ZjNetworkEmp getByAccountId(Long accountId) {
        return networkEmpMapper.getByAccountId(accountId);
    }

    // 根据服务商人员ID获取确认接单策略
    @Override
    public Boolean isAutoSureReceiveOrderById(Long id) {
        ZjNetworkEmp emp = this.getById(id);
        return null != emp && emp.getAutoSureReceiveOrder();
    }

    // 获取服务商人员及地址下拉数据
    @Override
    public Map<String, Object> getNetworkEmpAddressPageSelect(Long custAccId, SelectVo selectVo) {
        PageUtil.setSelectPageLimit(selectVo);
        List<ViewNetworkEmpDetail> networkEmpDetails = viewNetworkEmpDetailService.getNetworkEmpAddressPageSelect(custAccId, selectVo);
        List<ZjNetworkEmpAddress> empAddressList = networkEmpAddressService.getDefaultAddressByNetworkEmpIds(networkEmpDetails.stream().map(ViewNetworkEmpDetail::getId).toList());
        List<SelectEmpAddressVo> voList = networkEmpDetails.stream().map(emp -> {
            SelectEmpAddressVo vo = new SelectEmpAddressVo();
            vo.setId(emp.getId());
            vo.setName(emp.getAccountName());
            vo.setUsername(emp.getAccountName());
            vo.setPhone(emp.getAccountPhone());
            empAddressList.stream().filter(f -> Objects.equals(f.getNetworkEmpId(), emp.getId())).findFirst().ifPresent(addr -> {
                vo.setProvince(addr.getProvince());
                vo.setCity(addr.getCity());
                vo.setArea(addr.getArea());
                vo.setTown(addr.getTown());
                vo.setAddress(addr.getAddress());
            });
            return vo;
        }).toList();
        return PageUtil.pageList(selectVo.getPage(), selectVo.getLimit(), viewNetworkEmpDetailService.getNetworkEmpAddressPageSelectCount(custAccId, selectVo), voList);
    }

    // 根据商家获取服务人员下拉数据
    @Override
    public Map<String, Object> getNetworkEmpSelect(Long custAccId, SelectVo selectVo) {
        PageUtil.setSelectPageLimit(selectVo);
        long count = viewNetworkEmpDetailService.getNetworkEmpSelectCount(custAccId, selectVo);
        if (count <= 0) {
            return PageUtil.pageList(selectVo.getPage(), selectVo.getLimit(), count, new ArrayList<>());
        }
        List<ViewNetworkEmpDetail> networkEmpDetails = viewNetworkEmpDetailService.getNetworkEmpSelect(custAccId, selectVo);
        return PageUtil.pageList(selectVo.getPage(), selectVo.getLimit(), count, networkEmpDetails.stream().map(emp -> {
            return new SelectEmpVo(emp.getId(), emp.getAccountName(), emp.getAccountPhone());
        }));
    }

}
